import { ModdleElement } from 'bpmn-moddle'
import { getBusinessObject, is } from 'bpmn-js/lib/util/ModelUtil'
import { useSettingStore } from '@/store/bpmnProcess/settingStore'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'

export function isCandidateStarter(element): boolean {
  const businessObject = getBusinessObject(element)
  return is(element, 'bpmn:Process') || (is(element, 'bpmn:Participant') && businessObject.get('processRef'))
}

// CandidateStarterGroup
export function getCandidateStarterGroup(element): string | undefined {
  const prefix = useSettingStore().editor.processEngine
  const businessObject = getRelativeBusinessObject(element)
  return businessObject.get(`${prefix}:candidateStarterGroups`)
}
export function setCandidateStarterGroup(element, value: string | undefined) {
  const prefix = useSettingStore().editor.processEngine
  const modeling = useModelerStore().getModeling
  const businessObject = getRelativeBusinessObject(element)
  modeling.updateModdleProperties(element, businessObject, {
    [`${prefix}:candidateStarterGroups`]: value
  })
}

// CandidateStarterUsers
export function getCandidateStarterUsers(element): string | undefined {
  const prefix = useSettingStore().editor.processEngine
  const businessObject = getRelativeBusinessObject(element)
  return businessObject.get(`${prefix}:candidateStarterUsers`)
}
export function setCandidateStarterUsers(element, value: string | undefined) {
  const prefix = useSettingStore().editor.processEngine
  const modeling = useModelerStore().getModeling
  const businessObject = getRelativeBusinessObject(element)
  modeling.updateModdleProperties(element, businessObject, {
    [`${prefix}:candidateStarterUsers`]: value
  })
}

function getRelativeBusinessObject(element): ModdleElement {
  let businessObject
  if (is(element, 'bpmn:Process')) {
    businessObject = getBusinessObject(element)
  } else {
    businessObject = getBusinessObject(element).get('processRef')
  }
  return businessObject
}
